package com.le.high.class2;

import org.junit.Test;

/**
 * 一个 char 类型的数组 chs，其中所有的字符都不同。
 * 例如，chs=['A', 'B', 'C', ... 'Z']，则字符串与整数的对应关系如下:
 * A, B... Z, AA,AB...AZ,BA,BB...ZZ,AAA... ZZZ, AAAA...
 * 1, 2...26,27, 28... 52,53,54...702,703...18278, 18279...
 * 例如，chs=['A', 'B', 'C']，则字符串与整数的对应关系如下:
 * A,B,C,AA,AB...CC,AAA...CCC,AAAA...
 * 1, 2,3,4,5...12,13...39,40...
 * 给定一个数组 chs，实现根据对应关系完成字符串与整数相互转换的两个函数。
 * 思路：  K伪进制 取值 1。。。K
 */
public class Problem05_NumberAndString {

    // int -> string
    public static String getString(char[] chs, int n) {
        if (chs == null || chs.length == 0 || n < 1) {
            return "";
        }
        int cur = 1;
        int base = chs.length; // K伪进制 1..K
        int len = 0; // 需要几位，K^0,K^1,K^2...
        while (n >= cur) {
            len++;
            n -= cur;
            cur *= base;
        }
        char[] res = new char[len];
        int index = 0;
        int nCur = 0; // 当前字符位置，取值 1...26
        do {
            cur /= base; // K伪进制,阶数减一
            nCur = n / cur;
            res[index++] = getKthCharAtChs(chs, nCur + 1);
            n %= cur;
        } while (index != res.length);
        return String.valueOf(res);
    }

    // 返回k在chs中的元素
    public static char getKthCharAtChs(char[] chs, int k) {
        if (k < 1 || k > chs.length) {
            return 0;
        }
        return chs[k - 1];
    }

    public static int getNum(char[] chs, String str) {
        if (chs == null || chs.length == 0 || str == null || str.length() == 0) {
            return 0;
        }
        char[] s = str.toCharArray();
        int base = chs.length;
        int res = 0;
        int cur = 1;
        for (int i = s.length - 1; i != -1; i--) {
            res += getNthFromChar(chs,s[i]) * cur;
            cur *= base;
        }
        return res;
    }

    private static int getNthFromChar(char[] chs, char c) {
        int res = -1;
        for (int i = 0; i < chs.length; i++) {
            if (chs[i] == c){
                res = i + 1;
                break;
            }
        }
        return res;
    }


    @Test
    public void test() {
        char[] chs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z'};
        // A...AAB 1...704
//        for (int i = 1; i != 705; i++) {
//            System.out.print(getString(chs, i) + " ");
//            if (i % chs.length == 0) {
//                System.out.println();
//            }
//        }
        System.out.println();
        System.out.println("========================");
        int testNum = 53;
        System.out.println(getString(chs,testNum));
//        System.out.println(getNum(chs, getString(chs, testNum)));
//        String testStr = "BZZA";
//        System.out.println(getString(chs, getNum(chs, testStr)));
    }
}
